# -*- coding: utf-8 -*-
"""
Module Description: 时装称号变更方法
Date: 2017/11/22
Author: FQ
"""
from collections import defaultdict

from pyshare.dal.gameconfig.query import getProfile
from pyshare.dal.dal_adapters import cross_adapters as cross_adt
from pyshare.dal.repository_impl import CrossTitleOwnerRepository
from pyshare.const.enums.activity import ActivityClass
from pyshare.remote_services.area_services.title_service import AreaTitleService


class BaseTitleManager(object):
    """
    称号变更封装
    支持多人称号
    update: 优化：批量创建
    """

    def __init__(self, field_dict, new_owner_list, cfg=None):
        cfg = cfg if cfg else getProfile('TcTitle', **field_dict)
        self.title_id = cfg.TitleId if cfg else None
        self.old_owner_adt_dict = {}  # {rid: server_id}
        self.new_owner_list = new_owner_list  # [[[rid], server_id]]

    def is_need_change(self):
        """检测是否配置满足变更条件"""
        return False if not self.title_id else True

    def add_owner(self, is_push=1):
        """添加称号，这边主要用于永久的称号"""
        for rid_list, server_id in self.new_owner_list:
            new_list = [rid for rid in rid_list if rid not in self.old_owner_adt_dict]
            # 批量创建
            CrossTitleOwnerRepository.create_many([{'TitleId': self.title_id, 'RoleGuid': rid,
                                                    'ServerId': server_id} for rid in new_list])
            for rid in rid_list:
                # 调用区服服务添加称号
                AreaTitleService.add_cross_title(self.title_id, rid, is_push, server_id=server_id)

        return True

    def new_owner(self, is_push=1, server_list=None):

        for rid_list, server_id in self.new_owner_list:
            new_list = [rid for rid in rid_list if rid not in self.old_owner_adt_dict]
            # 批量创建
            CrossTitleOwnerRepository.create_many([{'TitleId': self.title_id, 'RoleGuid': rid,
                                                    'ServerId': server_id} for rid in new_list])
            # 调用区服服务变更称号
            AreaTitleService.change_cross_title(self.title_id, rid_list, is_push, server_id=server_id,
                                                server_list=server_list)

        return True

    def old_owner(self, check_server_old=True):
        """
        old owner 变更处理
        1. 活动类的称号变更 check_server_old可都设置成False,
        因为活动类的多人称号也只有一个区可以获得，
        在new_owner()时会检测并删除参与区服ServerList未获得此次称号的旧拥有者
        2. 全局称号，eg: 跨服国力榜称号
        这种类型的称号是全区全服的，check_server_old需要设置成 True ,因为没有ServerList, new_owner()不会去检测其他区服，
        而且全服全服都检测，效率很低
        :param check_server_old: 是否调用区服删除称号
        :return:
        """
        new_rid_list = []
        for rid_list, server_id in self.new_owner_list:
            new_rid_list += rid_list

        # 对比生成需要删除的rid
        need_del_dict = {}
        for rid, server_id in self.old_owner_adt_dict.iteritems():
            if rid in new_rid_list:
                continue
            if server_id not in need_del_dict:
                need_del_dict[server_id] = []
            need_del_dict[server_id].append(rid)

        # 根据区服批量删除称号
        for server_id, rid_list in need_del_dict.iteritems():
            CrossTitleOwnerRepository.delete_by_titleid_rid_list_serverid(title_id=self.title_id,
                                                                          rid_list=rid_list, server_id=server_id)
            # # 调用区服服务删除称号
            if check_server_old:
                AreaTitleService.del_cross_title(self.title_id, rid_list, 1, server_id=server_id)


class CrossRankTitleManager(BaseTitleManager):
    """
    跨服冲榜称号变更管理
    不显示在明君殿
    """

    def __init__(self, activity_type, new_owner_list, server_id_list):
        """
        :param activity_type:
        :param new_owner_list: [[[rid], server_id]]
        """
        field_dict = {'ActivityType': activity_type, 'ActivityClass': ActivityClass.CrossRank}
        super(CrossRankTitleManager, self).__init__(field_dict, new_owner_list)
        self.old_owner_adt_dict = {t.role_guid: t.server_id for t in
                                   CrossTitleOwnerRepository.filter_by_titleid_serverid_list(self.title_id,
                                                                                             server_id_list)}


class CrossLeaderBoardTitleManage(BaseTitleManager):
    """
    跨服榜单称号管理
    """

    def __init__(self, new_owner_list, title_cfg):
        """
        :param new_owner_list: [[[rid], server_id]]
        """
        field_dict = {}
        super(CrossLeaderBoardTitleManage, self).__init__(field_dict, new_owner_list, cfg=title_cfg)
        self.old_owner_adt_dict = {t.role_guid: t.server_id for t in
                                   CrossTitleOwnerRepository.filter_by_titleid(self.title_id)}


class CrossSiegeTitleManager(BaseTitleManager):
    """
    跨服攻城战称号变更管理
    不显示在明君殿
    """

    def __init__(self, new_owner_list, server_id_list, title_id):
        """
        :param new_owner_list: [[[rid], server_id]]
        """
        field_dict = {'TitleId': title_id}
        super(CrossSiegeTitleManager, self).__init__(field_dict, new_owner_list)
        self.old_owner_adt_dict = {t.role_guid: t.server_id for t in
                                   CrossTitleOwnerRepository.filter_by_titleid_serverid_list(self.title_id,
                                                                                             server_id_list)}


class CrossRuinsTitleManager(CrossSiegeTitleManager):
    """
    跨服遗迹称号变更管理
    """


class CrossChessTitleManager(CrossSiegeTitleManager):
    """
    跨服棋局称号变更管理
    """


class CrossSoccerTitleManager(CrossSiegeTitleManager):
    """
    跨服足球称号变更管理
    """


class CrossRehearseTitleManager(CrossSiegeTitleManager):
    """
    跨服健锐称号变更管理
    """


class CrossNaadamTitleManager(CrossSiegeTitleManager):
    """"
    跨服那达慕称号变更管理
    """


class CrossContendTitleManager(CrossSiegeTitleManager):
    """"
    跨服百家争鸣称号变更管理
    """


class CrossQueenTitleManager(CrossSiegeTitleManager):
    """
    跨服健锐称号变更管理
    """


class CrossBanquetTitleManager(CrossSiegeTitleManager):
    """
    跨服满汉全席称号变更管理
    """


class CrossIslandTitleManager(BaseTitleManager):
    """
    跨服蓬莱仙岛称号变更
    """

    def __init__(self, new_owner_list, server_id_list, title_id):
        """
        :param new_owner_list: [[[rid], server_id]]
        :param server_rid_dict: {server_id: [rid]} 所有可获取称号玩家rid及区服汇总
        """
        field_dict = {'TitleId': title_id}
        super(CrossIslandTitleManager, self).__init__(field_dict, new_owner_list)
        self.old_owner_adt_dict = {t.role_guid: t.server_id for t in
                                   CrossTitleOwnerRepository.filter_by_titleid_serverid_list(self.title_id,
                                                                                             server_id_list)}

    def change_title(self, server_list, is_push=1):
        """
        批量创建、删除多区服称号
        :param server_list: 活动参与区服id列表
        :param is_push 是否推送称号变更
        """
        new_rid_list = []
        for rid_list, server_id in self.new_owner_list:
            new_rid_list += rid_list  # 所有可获得称号玩家
            new_list = [rid for rid in rid_list if rid not in self.old_owner_adt_dict]  # 可获得称号但目前未拥有
            # 批量创建
            CrossTitleOwnerRepository.create_many([{'TitleId': self.title_id, 'RoleGuid': rid,
                                                    'ServerId': server_id} for rid in new_list])

        # 对比生成需要删除的rid
        need_del_dict = defaultdict(list)
        for rid, server_id in self.old_owner_adt_dict.iteritems():
            if rid in new_rid_list:
                continue
            need_del_dict[server_id].append(rid)

        # 根据区服批量删除称号
        for server_id, rid_list in need_del_dict.iteritems():
            CrossTitleOwnerRepository.delete_by_titleid_rid_list_serverid(title_id=self.title_id,
                                                                          rid_list=rid_list, server_id=server_id)

        # 随机挑选一个区服调用创建和删除所有区服称号
        if server_list:
            server_id = server_list[0]
            AreaTitleService.change_many_server_cross_title(self.title_id, self.new_owner_list, server_list, is_push,
                                                            server_id)


class CrossSeasonTitleManager(BaseTitleManager):
    """
    九州之巅称号变更管理
    不显示在明君殿
    """

    def __init__(self, new_owner_list, title_id):
        """
        :param new_owner_list: [[[rid], server_id]]
        """
        field_dict = {'TitleId': title_id}
        super(CrossSeasonTitleManager, self).__init__(field_dict, new_owner_list)
        self.old_owner_adt_dict = {t.role_guid: t.server_id for t in
                                   CrossTitleOwnerRepository.filter_by_titleid(self.title_id)}

    def change_title(self, is_push=1):
        """
        批量创建、删除多区服称号
        :param is_push 是否推送称号变更
        """
        new_rid_list = []
        server_list = []
        for rid_list, server_id in self.new_owner_list:
            new_rid_list += rid_list  # 所有可获得称号玩家
            new_list = [rid for rid in rid_list if rid not in self.old_owner_adt_dict]  # 可获得称号但目前未拥有
            # 批量创建
            CrossTitleOwnerRepository.create_many([{'TitleId': self.title_id, 'RoleGuid': rid,
                                                    'ServerId': server_id} for rid in new_list])
            server_list.append(server_id)

        # 对比生成需要删除的rid
        need_del_dict = defaultdict(list)
        for rid, server_id in self.old_owner_adt_dict.iteritems():
            if rid in new_rid_list:
                continue
            need_del_dict[server_id].append(rid)
            server_list.append(server_id)

        # 根据区服批量删除称号
        for server_id, rid_list in need_del_dict.iteritems():
            CrossTitleOwnerRepository.delete_by_titleid_rid_list_serverid(title_id=self.title_id,
                                                                          rid_list=rid_list, server_id=server_id)

        # 随机挑选一个区服调用创建和删除所有区服称号
        if server_list:
            server_id = server_list[0]
            AreaTitleService.change_many_server_cross_title(self.title_id, self.new_owner_list, server_list, is_push,
                                                            server_id)


class CrossClearanceTitleManager(CrossIslandTitleManager):
    """
    跨服三消称号变更管理
    """


class CrossMonopolyTitleManager(CrossIslandTitleManager):
    """
    跨服大富翁称号变更管理
    """


class CrossSiegelordTitleManager(BaseTitleManager):
    """
    跨服攻城略地
    """
    def __init__(self, new_owner_list, title_id, server_id_list):
        """
        :param new_owner_list: [[[rid], server_id]]
        """
        field_dict = {'TitleId': title_id}
        super(CrossSiegelordTitleManager, self).__init__(field_dict, new_owner_list)
        self.old_owner_adt_dict = {t.role_guid: t.server_id for t in
                                   CrossTitleOwnerRepository.filter_by_titleid_serverid_list(self.title_id,
                                                                                             server_id_list)}

    def change_title(self, server_list, is_push=1):
        """
        批量创建、删除多区服称号
        :param server_list: 活动参与区服id列表
        :param is_push 是否推送称号变更
        """
        new_rid_list = []
        for rid_list, server_id in self.new_owner_list:
            new_rid_list += rid_list  # 所有可获得称号玩家
            new_list = [rid for rid in rid_list if rid not in self.old_owner_adt_dict]  # 可获得称号但目前未拥有
            # 批量创建
            CrossTitleOwnerRepository.create_many([{'TitleId': self.title_id, 'RoleGuid': rid,
                                                    'ServerId': server_id} for rid in new_list])

        # 对比生成需要删除的rid
        need_del_dict = defaultdict(list)
        for rid, server_id in self.old_owner_adt_dict.iteritems():
            if rid in new_rid_list:
                continue
            need_del_dict[server_id].append(rid)

        # 根据区服批量删除称号
        for server_id, rid_list in need_del_dict.iteritems():
            CrossTitleOwnerRepository.delete_by_titleid_rid_list_serverid(title_id=self.title_id,
                                                                          rid_list=rid_list, server_id=server_id)

        # 随机挑选一个区服调用创建和删除所有区服称号
        if server_list:
            server_id = server_list[0]
            AreaTitleService.change_many_server_cross_title(self.title_id, self.new_owner_list, server_list, is_push,
                                                            server_id)


class CrossCeladonTitleManager(CrossIslandTitleManager):
    """
    跨服青瓷御器称号变更管理
    """


class CrossFightTitleManager(CrossIslandTitleManager):
    """
    皇决之选--称号变更管理
    """


class CrossTowerTitleManager(CrossIslandTitleManager):
    """
    跨服爬塔称号变更管理
    """


class CrossFishTitleManager(CrossIslandTitleManager):
    """
    跨服御海垂纶称号变更管理
    """